package com.howtodoinjava.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.howtodoinjava.entity.User;
import com.howtodoinjava.services.UserService;

@Service
public class MyUserContext implements UserContext {

	@Autowired
	UserService userService;

	@Transactional
	public User getCurrentUser() {
		SecurityContext context = SecurityContextHolder.getContext();
		Authentication authentication = context.getAuthentication();
		if (authentication == null) {
			return null;
		}
		String userName = authentication.getName();
		return userService.getUserByName(userName);

		// get userdetails with securitycontext.
		// UserDetails userDetails =
		// (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		// System.out.println(ToStringBuilder.reflectionToString(userDetails));
		// return null;
	}

	/**
	 * user for sign-up controller of course after sign-up that user is
	 * authenticated
	 */
	public void setCurrentUser(User user) {
		UserDetails userDetails = userService
				.getUserDetails(user.getUserName());
		Authentication authentication = new UsernamePasswordAuthenticationToken(
				userDetails, user.getPassword(), userDetails.getAuthorities());
		SecurityContextHolder.getContext().setAuthentication(authentication);
	}

}
